/**
 * Tiem: 2023-1-16
 * FileName: Driver Manage(司机管理)
 * Editor: Haidong
*/

import React, { Component } from "react";
import TheQueryForm from '@/components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend';
import store from "@/store/store";
import TheButton from "@/components/TheButton";
import TheImage from '@/components/TheImage';
import ThePagination from "@/components/ThePagination";
import { Table, Space, Radio } from "antd";
import { apiPostChauffeurPage, apiPutChauffeurBatchUpdateStatus } from "@/request/petTaxi";
import { getDateTime3 } from '@/utils/getDate';
import chauffeurAvatar from '@/assets/images/chauffeur-avatar.png'
import _ from 'lodash';
import "./style/index.less";

class Chauffeur extends Component {
    constructor(props) {
        super();
        this.queryFormRef = React.createRef()
        this.heightRef = React.createRef()
        this.searchRef = React.createRef()
        this.pageHeight = React.createRef()
        this.state = {
            form_show: true,
            down_loading: false,
            columns: [
                {
                    title: "创建时间",
                    dataIndex: "createTime",
                    key: "createTime",
                },
                {
                    title: "账号ID",
                    dataIndex: "id",
                    key: "id",
                },
                {
                    title: "账号UUID",
                    dataIndex: "driverId",
                    key: "driverId",
                },
                {
                    title: "账号名",
                    dataIndex: "username",
                    key: "username",
                },
                {
                    title: "手机号",
                    dataIndex: "phone",
                    key: "phone",
                },
                {
                    title: "头像",
                    dataIndex: "avatar",
                    key: "avatar",
                    render: (text, render) => {
                        return <TheImage src={text !== "" ? text : chauffeurAvatar} width={80} height={80} />
                    }
                },
                {
                    title: "昵称",
                    dataIndex: "nickname",
                    key: "nickname",
                },
                {
                    title: "状态",
                    dataIndex: "status",
                    key: "status",
                    render: (text, render) => {
                        let status = ''
                        switch (text) {
                            case 1:
                                status = '正常'
                                break;
                            case 2:
                                status = '禁用'
                                break;
                            default:
                                break;
                        }
                        return status
                    }
                },
                {
                    title: "备注",
                    dataIndex: "remark",
                    key: "remark",
                },
                {
                    title: "操作",
                    fixed: 'right',
                    key: 'right',
                    width: 200,
                    render: (text, render) => {
                        return <div>
                            <TheButton haspermi={['Taxi:Chauffeur:view']} onClick={() => this.view(render.driverId, "view")}>查看</TheButton>
                            <TheButton haspermi={['Taxi:Chauffeur:status']} onClick={() => this.enable(render.driverId, render.status)}>
                                {render.status === 1 ? "禁用" : "启用"}</TheButton>
                            <TheButton haspermi={['Taxi:Chauffeur:edit']} onClick={() => this.view(render.driverId, "edit")}>编辑</TheButton>
                        </div>
                    }
                },
            ],
            pageData: {
                pageNo: 1,
                pageSize: 10
            },
            total: "",
            newColumns: [],
            dataSource: [],
            queryForm: {},
            searchOption: [
                { field: 'keyword', label: '搜索', placeholder: '请输入搜索关键字', required: false, rules: [], type: 'Input', tooltip: "包含账号名，手机号，昵称，UUID", defaultValue: '' },
                { field: 'time', label: '创建时间', placeholder: '', required: false, rules: [], type: 'RangePicker', defaultValue: '' },
            ],
            tableHeight: '',
            Height: '',
            selectedKeys: { 1: [] },
            status: ""
        }
    }
    //Initialization
    componentDidMount() {
        this.onColumnsFilter(this.state.columns)
        let searchParams = store.getState().searchValue
        let { pageNo, pageSize, queryForm, status ,pathName} = searchParams
        let Height = this.pageHeight.current.clientHeight - this.searchRef.current.offsetHeight - 50
        let tableHeight = Height - 150
        this.setState({
            tableHeight,
            Height
        })
        if (searchParams && pageNo &&pathName=='petTaxi') {
            this.setState({
                queryForm,
                status,
                pageData: {
                    pageNo, pageSize
                }
            }, () => {
                this.queryFormRef.onSetDefault({
                    ...queryForm
                })
                this.getData()
            })
        } else {
            this.getData()
        }
    }
    //CTRL
    //表格title
    onColumnsFilter(value) {
        this.setState({
            newColumns: value
        })
    }
    //获取数据
    getData = async (values) => {
        const { status } = this.state
        let { pageNo, pageSize } = this.state.pageData
        if (values && !_.isEmpty(values.time)) {
            values.startCreateTime = getDateTime3(values.time[0]) + ' 00:00:00'
            values.endCreateTime = getDateTime3(values.time[1]) + ' 23:59:59'
            delete (values.time)
        }
        this.setState({
            queryForm: values === undefined ? this.state.queryForm : { ...values, }
        }, async () => {
            const params = {
                pageNo, pageSize, status, ...this.state.queryForm
            }
            store.dispatch({
                type: 'SaveSearchValues',
                data: {
                    pathName:'petTaxi',
                    ...params
                }
            })
            let res = await apiPostChauffeurPage({ ...params })
            if (res.code === 0 && res.data) {
                this.setState({ dataSource: res.data, pageData: { pageNo: res.pageNo, pageSize: res.pageSize }, total: res.totalCount })
            }
        })
    }
    //分页查询
    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo, pageSize
            }
        }, () => {
            this.getData()
        })
    }
    //重置
    onReset() {
        this.setState({
            status: "",
            queryForm: {}
        }, () => {
            this.pageChange(1, 10)
        })
    }
    //搜索
    onFormSearch(values) {
        this.setState({
            pageData: { pageNo: 1, pageSize: 10 }
        }, () => {
            this.getData(values)
        })
    }

    //状态按钮切换
    handleStatusChange = (e) => {
        let { queryForm, status } = this.state
        status = e.target.value
        this.setState({
            queryForm,
            status
        }, () => {
            this.queryFormRef.onSetDefault({
                ...queryForm
            })
            this.getData()
        })
    }
    //查看详情
    view = (code, type) => {
        this.props.history.push(`/chauffeur/detail/${code}/${type}`);
    }
    //批量禁用/启用
    enable = (driverId, type) => {
        let content = ''
        let status = ''
        if (type === 1) {
            content = "禁用"
            status = 2
        } else {
            content = "启用"
            status = 1
        }
        if (!driverId) {
            React.$message({
                type: 'warning',
                content: `请先勾选需要${content}的员工！`
            })
            return false
        }
        React.$confirm({
            title: "提示",
            type: 'warning',
            content: `是否确定${content}员工！`,
            onOk: async () => {
                let res = await apiPutChauffeurBatchUpdateStatus({ driverIds: driverId, status })
                if (res.code === 0) {
                    React.$message({
                        type: 'success',
                        content: res.data
                    })
                    this.setState({
                        selectedKeys: { 1: [] },
                        ids: ''
                    })
                    this.getData()
                    return false

                } else {
                    React.$message({
                        type: 'warning',
                        content: res.codeMessage
                    })
                    return false
                }
            }
        })
    }
    //批量勾选
    onChange = (selectedRowKeys, selectedRows) => {
        let pageNo = this.state.pageData.pageNo
        let selectedKeys = { ...this.state.selectedKeys }
        selectedKeys[pageNo] = selectedRowKeys
        let ids = ""
        Object.values(selectedKeys).forEach(value => {
            if (value.length > 0) {
                ids += value.toString() + ","
            }
        })
        this.setState({
            selectedKeys,
            ids
        })
    }
    //View
    render() {
        let { columns, form_show, searchOption, newColumns, dataSource, pageData, total, selectedKeys, ids, status } = this.state
        const rowSelection = {
            selectedRowKeys: selectedKeys[pageData.pageNo],
            onChange: this.onChange,
        }
        return (
            <div className='missionsPage' ref={this.pageHeight}>
                <div ref={this.searchRef}>
                    <div style={{ marginBottom: "10px" }}>
                        <TheButton haspermi={['Taxi:Chauffeur:add']} size="middle" onClick={() => this.view("add", null)} type="primary">添加员工</TheButton>
                    </div>
                    <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
                        onReset={() => this.onReset()}
                        onGetValues={(values) => this.onFormSearch(values)} >
                    </TheQueryForm>
                    <TheTableExtend
                        columns={columns}
                        onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
                        onTableRefresh={() => this.getData()}
                        onColumnsFilter={(value) => this.onColumnsFilter(value)}
                    >
                        <Space direction="vertical" size="middle" style={{ marginBottom: '10px' }}>
                            <Radio.Group value={status} onChange={this.handleStatusChange}>
                                <Radio.Button value="">全部</Radio.Button>
                                <Radio.Button value="1">正常</Radio.Button>
                                <Radio.Button value="2">已禁用</Radio.Button>
                            </Radio.Group>
                            <div>
                                <Space>
                                    <TheButton size="middle" onClick={() => this.enable(ids, 1)} type="default">禁用</TheButton>
                                    <TheButton size="middle" onClick={() => this.enable(ids, 2)} type="default">启用</TheButton>
                                </Space>
                            </div>
                        </Space>
                    </TheTableExtend>

                </div>
                <div className='p-layout-content-pagination'>
                    <Table columns={newColumns} dataSource={dataSource} pagination={false} bordered={1}
                        scroll={{ x: 'max-content', y: '55vh' }} rowKey={record => record.driverId}
                        rowSelection={rowSelection}
                    ></Table>
                    <ThePagination
                        pageNo={pageData.pageNo}
                        pageSize={pageData.pageSize}
                        total={total}
                        pageChange={this.pageChange}
                    />
                </div>

            </div>
        )
    }

}

export default Chauffeur